import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RestService } from './../../services/rest.service';
import { ElasticsearchService } from './../../services/elasticsearch.service';
import { GridOptions } from 'ag-grid/main';
import { FormControl } from '@angular/forms';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
  selector: 'app-fault',
  templateUrl: './fault.component.html',
  styleUrls: ['./fault.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class FaultComponent implements OnInit {
  gridOptions: GridOptions;
  columnDefs: any[];
  rowData: any[];
  selectedTrain: string;
  queryIP = false;

  fromTime;
  toTime;

  constructor(public elastic: ElasticsearchService, public restService: RestService) {
    this.gridOptions = this.restService.getGeneralGridOptions();
    this.gridOptions.overlayNoRowsTemplate = '<span class="csf-overlay">无故障数据</span>';
    this.columnDefs = this.buildColumnDefs();
    this.selectedTrain = '列车001';
    this.rowData = [];
  }

  buildColumnDefs() {
    const columnDefs = [];
    columnDefs.push({
      headerName: '列车号',
      field: 'train',
      maxWidth: 150
    }, {
      headerName: '故障时间',
      field: 'time',
      maxWidth: 200
    }, {
      headerName: '故障描述',
      field: 'name',
      minWidth: 200
    });

    return columnDefs;
  }

  fromChange(event) {
    this.fromTime = event.value.getTime();
  }

  toChange(event) {
    this.toTime = new Date(event.value).setHours(23, 59, 59, 999);
  }

  query(event) {
    this.queryIP = true;
    this.gridOptions.api.showLoadingOverlay();
    this.elastic.getLastFaults(this.fromTime, this.toTime, data => {
      this.rowData = data;
      this.queryIP = false;
    });
  }

  buildCurrentFault() {
    const data = this.elastic.lastRecord;
    if (!data || !_.isArray(data) || _.isEmpty(data)) {
      this.rowData = [];
      return;
    }

    const faults = this.restService.getFaults(data[0]);
    if (_.isEmpty(faults)) {
      this.rowData = [];
      return;
    }

    const updateTime = this.restService.getUpdatedTime(data[0]);
    this.rowData = [];
    faults.forEach(fault => {
      this.rowData.push({
        train: '001',
        time: updateTime,
        name: fault
      });
    });
  }

  onGridReady(params) {
    params.api.sizeColumnsToFit();
  }

  selectAllRows() {
    this.gridOptions.api.selectAll();
  }

  ngOnInit() {
  }
}
